#coding:utf-8
import json, re
from django.core.mail import EmailMessage
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.template.loader import render_to_string
from lovewith.account.views.auth import sign_with_email
from lovewith.account.views.modules.noticeapi import NoticeApi
from lovewith.account.views.modules.userapi import UserApi
from lovewith.account.views.modules.weddingapi import WeddingApi
from lovewith.album.views.modules.album import AlbumApi
from lovewith.api.qiniu import Qiniu
from lovewith.api.t import WbControlCenter
from lovewith.settings import SITE_URL, FILE_UPLOAD_PATH
from lovewith.share.views.modules.share import ShareApi
from lovewith.supplier.views.modules.supplierapi import SupplierApi
from lovewith.website.views.modules.province import ProvinceApi
from lovewith.settings import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
from lovewith.subscribe.views.subscribe import get_subscribe_by_user



#获取分页订阅数据
@login_required
def get_user_subscribe_by_page(request):
    page_no = int(request.GET.get('page') or 1)
    tag = request.GET.get('tag')

    if tag == 'all':
        sub_data = get_subscribe_by_user(request.user, page_no)
        share_data = {
            'page': page_no,
            'data': sub_data.get('share')
        }
    else:
        sub_data = ShareApi().get_by_tag(tag, page_no)
        share_data = {
            'page': page_no,
            'data': sub_data.get('share')
        }

    return HttpResponse(json.dumps(share_data))


#根据album获取分享信息
def get_share_by_album(request):
    album_id = request.GET.get('aid')
    page_no = int(request.GET.get('page') or 1)
    album_share_data = AlbumApi().get_share_by_album(album_id, page_no)

    share_data = {
        'page': page_no,
        'data': album_share_data.get('share')
    }

    return HttpResponse(json.dumps(share_data))


#判断用户名是否重复
def check_username(request):
    email = request.GET.get('email')
    username = request.GET.get('username')

    if email:
        result = UserApi.check_user(email=email)
    if username:
        result = UserApi.check_user(username=username)

    if result:
        result = {'error': True}
    else:
        result = {'error': False}

    return HttpResponse(json.dumps(result))


#提交登录
def sign(request):
    email = request.POST.get('mail')
    pwd = request.POST.get('pwd')
    result = {'error': True, 'msg': u'用户名或密码错误'}

    if email and pwd:
        stat = sign_with_email(request, email, pwd)
        if stat:
            result = {'error': False}

    return HttpResponse(json.dumps(result))


#提交注册
def join(request):
    app_uid = request.POST.get('app_uid')
    token = request.POST.get('token')
    expires = request.POST.get('expires')
    email = request.POST.get('email')
    pwd = request.POST.get('pwd') or '!#@$#%$^%&^*&(*)'
    app_username = request.POST.get('app_username')
    username = request.POST.get('username')
    avatar = request.POST.get('avatar')
    gender = request.POST.get('gender') or 'm'
    account_type = request.POST.get('account_type') or 3
    result = {'error': True, 'msg': u'系统错误'}

    #保存头像
    if avatar and avatar != '':
        if avatar.find('mt-temp.qiniudn.com') > -1:
            #移动图片
            avatar = Qiniu('mt-temp').move(avatar, 'mt-avatar')
        else:
            #保存远程服务器图片
            avatar = Qiniu('mt-temp').save_remote(avatar, 'mt-avatar')
    else:
        avatar = 'http://mt-avatar.qiniudn.com/avatar.gif'

    if email and pwd and username and avatar and gender:
        user_app_data = None
        user_name_data = UserApi.check_user(username=username)
        user_email_data = UserApi.check_user(email=email)
        if app_uid:
            user_app_data = UserApi.check_data(app_uid=app_uid, account_type=account_type)

        if not user_name_data and not user_email_data and not user_app_data:
            site_user = UserApi.add(
                password=pwd,
                app_uid=app_uid,
                username=username,
                email=email,
                gender=gender,
                avatar=avatar,
                account_type=account_type
            )
            if site_user:
                #保存token
                if token and expires and app_username and account_type != 3:
                    UserApi.update_auth(site_user, account_type, app_username, token, expires)

                sign_with_email(request, email, pwd)

                #关注官方微博
                WbControlCenter(site_user).follow_us()
                #同步微博
                text = u'关注婚礼的一切，分享最美好的时光，这里有你需要的婚礼灵感，各种超美婚纱婚品，向往的蜜月胜地和家居创意，我在这里@我的婚礼时光，赶快来吧 >> %s' % SITE_URL
                WbControlCenter(site_user).send_media(text, '%sother/weibo_reg.jpg' % FILE_UPLOAD_PATH, sync_wb=True)

                result = {'error': False}

    return HttpResponse(json.dumps(result))


#更新用户基础数据
@login_required
def update_user_base_data(request):
    user_data = request.user
    phone = request.POST.get('phone')
    qq = request.POST.get('qq')
    gender = request.POST.get('gender')
    province = request.POST.get('province')
    city = request.POST.get('city')
    email = request.POST.get('email')
    new_pwd = request.POST.get('new_pwd')
    result = {'error': True}

    #修改基本资料
    if phone and qq and gender and province and city:
        province_data = ProvinceApi.check_data(pid=province)
        city_data = ProvinceApi.check_data(cid=city)
        if province_data and city_data:
            user_data.phone = phone
            user_data.qq = qq
            user_data.gender = gender
            user_data.province = province_data
            user_data.city = city_data
            user_data.save()

            result = {'error': False}

    #修改email
    if email:
        is_math = bool(re.match(r"^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$", email, re.VERBOSE))
        if is_math:
            user_data.email = email
            user_data.save()

            result = {'error': False}

    #修改密码
    if new_pwd:
        user_data.set_password(new_pwd)
        user_data.save()

        result = {'error': False}

    return HttpResponse(json.dumps(result))


#更新头像
@login_required
def update_avatar(request):
    user_data = request.user
    result = {'error': True}
    attach = request.POST.get('avatar')

    if attach:
        avatar = None
        if attach.find('mt-temp.qiniudn.com') > -1:
            #移动图片
            avatar = Qiniu('mt-temp').move(attach, 'mt-avatar')
        else:
            #保存远程服务器图片
            avatar = Qiniu('mt-temp').save_remote(attach, 'mt-avatar')

        if avatar:
            if user_data.avatar.find('avatar.gif') == -1:
                Qiniu('mt-avatar').delete(user_data.avatar)
            user_data.avatar = avatar
            user_data.save()

            result = {'error': False}

    return HttpResponse(json.dumps(result))


#更新授权信息
@login_required
def update_auth_data(request):
    token = request.POST.get('token')
    expires = request.POST.get('expires')
    account_type = request.POST.get('account_type')
    username = request.POST.get('username')

    if token and expires and type and username:
        UserApi.update_auth(request.user, account_type, username, token, expires)

    return HttpResponse(json.dumps({'error': False}))


#删除授权信息
@login_required
def delete_auth_data(request):
    account_type = request.POST.get('type')
    UserApi.delete_auth(request.user.id, account_type)

    return HttpResponse(json.dumps({'error': False}))


#更新同步状态
@login_required
def update_sync(request):
    account_type = request.POST.get('type')
    album = request.POST.get('album') or 0
    post = request.POST.get('post') or 0
    comment = request.POST.get('comment') or 0
    like = request.POST.get('like') or 0

    #{"post": "1", "comment": "1", "like": "1", "album": "1"}
    sync_data = json.dumps({
        'post': post,
        'comment': comment,
        'like': like,
        'album': album,
    })

    UserApi.update_sync(request.user.id, account_type, sync_data)

    return HttpResponse(json.dumps({'error': False}))


#更新BIZ信息
@login_required
def update_biz_data(request):
    fullname = request.POST.get('fullname')
    phone = request.POST.get('phone')
    qq = request.POST.get('qq')
    result = {'error': True}

    if fullname and phone and qq:
        post_states = UserApi.update_biz_data(request.user, fullname, phone, qq)
        if post_states > 0:
            result = {'error': False}

    return HttpResponse(json.dumps(result))


#获取婚礼信息
@login_required
def get_wedding_data(request):
    result = {}
    wedding_data = WeddingApi.check_data(request.user.id)
    if wedding_data:
        result = {
            'bride': wedding_data.bride,
            'bridegroom': wedding_data.bridegroom,
            'wedding_date': wedding_data.wedding_date,
            'wedding_time':  wedding_data.wedding_time,
            'city': wedding_data.city,
            'user_role': wedding_data.user_role,
            'phone': wedding_data.user.phone,
            'qq': wedding_data.user.qq
        }

    return HttpResponse(json.dumps(result))


#更新婚礼信息
@login_required
def update_wedding_data(request):
    self_name = request.POST.get('wed-self-name')
    self_role = request.POST.get('wed-self-role')
    other_name = request.POST.get('wed-other-name')
    other_role = request.POST.get('wed-other-role')
    date = request.POST.get('wed-date')
    hours = request.POST.get('wed-hours')
    minutes = request.POST.get('wed-minutes')
    city = request.POST.get('wed-city')
    address = request.POST.get('wed-address')

    if self_name and self_role and other_name and other_role:
        if date and hours and minutes and city and address:
            self_role = int(self_role)

            if self_role == 1:
                #用户角色为新郎
                bride = other_name
                bridegroom = self_name
            else:
                bride = self_name
                bridegroom = other_name

            wedding_time = '%s时%s分' % (hours, minutes)

            WeddingApi().update(
                bride=bride,
                bridegroom=bridegroom,
                wedding_date=date,
                wedding_time=wedding_time,
                city=city,
                address=address,
                user_role=int(self_role),
                user=request.user
            )

    return HttpResponse(json.dumps({'error': False}))


#获取未读通知数
@login_required
def get_unread_notice_count(request):
    notice_count = NoticeApi.get_count_by_user(request.user.id, notice_type='unread')
    return HttpResponse(json.dumps({'count': notice_count}))


#获取分页通知
@login_required
def get_notice_by_page(request):
    page_no = int(request.GET.get('p') or 2)
    notice_type = request.GET.get('t') or 'all'
    notice_data = []

    notice_filter_data = NoticeApi().get_by_page(request.user.id, page_no, notice_type)
    for d in notice_filter_data:
        notice_data.append({
            'id': d.id,
            'has_read': d.has_read,
            'title': d.title,
            'date': d.notice_date.strftime('%Y-%m-%d %H:%M:%S')
        })

    return HttpResponse(json.dumps({'data': notice_data}))


#删除通知
@login_required
def delete_notice(request):
    notice_id = request.GET.get('nid')
    notice_data = NoticeApi.check_data(notice_id, request.user.id)
    if notice_data:
        notice_data.delete()

    return HttpResponse(json.dumps({'error': False}))


#上传头像
def upload_avatar(request):
    attach = request.FILES.get('file', None)
    avatar_path = Qiniu('mt-temp').upload(attach)

    return HttpResponse(json.dumps(avatar_path))


#更新商家自定义分类
@login_required
# def update_biz_cate(request):
#     cate_id = request.POST.get('cate_id')
#     cate_name = request.POST.get('name')
#     action = request.GET.get('action')
#
#     supplier_data = SupplierApi.check_data(user_id=request.user.id)
#     if supplier_data:
#         if action == 'del' and request.GET.get('cate_id'):
#             cate_data = SupplierApi.validate_cate(int(request.GET.get('cate_id')))
#             if cate_data:
#                 cate_data.delete()
#         else:
#             if request.user.group_id == 3 and cate_name:
#                 new_cate_id = SupplierApi().add_biz_cate(cate_name, cate_id, request.user.id)
#
#             return HttpResponse(json.dumps({'cid': new_cate_id}))
#
#     return HttpResponse(json.dumps({}))


#更新预定用户信息
@login_required
def update_reserve_data(request):
    user = request.user
    wed_self_name = request.POST.get('wed-self-name', None)
    wed_self_role = request.POST.get('wed-self-role', None)
    wed_date = request.POST.get('wed-date', None)
    wed_city = request.POST.get('wed-city', None)
    wed_phone = request.POST.get('phone', None)
    wed_qq = request.POST.get('qq', None)

    if wed_self_name and wed_self_role and wed_date and wed_city and wed_phone and wed_qq:
        bride = wed_self_name
        bridegroom = ''

        if wed_self_role == '2':
            bride = ''
            bridegroom = wed_self_name

        WeddingApi().update(
            bride=bride,
            bridegroom=bridegroom,
            wedding_date=wed_date,
            city=wed_city,
            user_role=int(wed_self_role),
            user=user
        )

        user.full_name = wed_self_name
        user.phone = wed_phone
        user.qq = wed_qq
        user.save()

        return HttpResponse(json.dumps({'error': False}))

    return HttpResponse(json.dumps({'error': True}))


#发送忘记密码的邮件
def send_get_password_mail(request):
    email = request.GET.get('email')

    if email:
        user_data = UserApi.check_user(email=email)
        if user_data:
            try:
                #添加一条找回密码的记录
                confirm_key = UserApi.add_getpassword_log(user_data)
                content = render_to_string('edm/get-password.jinja', {
                    'username': user_data.username,
                    'reset_link': 'http://www.lovewith.me/u/getpasswd/?k=%s' % confirm_key
                })
                msg = EmailMessage(u'婚礼时光(www.lovewith.me) -- 找回密码', content, EMAIL_HOST_USER, [user_data.email])
                msg.content_subtype = 'html'
                msg.send()
            except StandardError:
                pass

    return HttpResponse(json.dumps({}))


#保存新密码
def save_new_password(request):
    confirm_key = request.POST.get('key')
    password = request.POST.get('pwd')
    if confirm_key and password:
        confirm_data = UserApi.validate_getpwd_key(confirm_key)
        if confirm_data:
            confirm_data.used = True
            confirm_data.save()

            user_data = confirm_data.user
            user_data.set_password(password)
            user_data.save()

            return HttpResponse(json.dumps({'error': False}))

    return HttpResponse(json.dumps({'error': True}))
